package com.znsd.zl.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.znsd.zl.order.dao.IOrderDao;
import com.znsd.zl.order.dao.RentDao;
import com.znsd.zl.order.entity.ContractEntity;
import com.znsd.zl.order.entity.OrderEntity;
import com.znsd.zl.order.entity.TradeOrderEntity;
import com.znsd.zl.order.entity.vo.HouseRentVo;
import com.znsd.zl.order.entity.vo.OrderEntityVo;
import com.znsd.zl.order.entity.vo.UserOrderVo;
import com.znsd.zl.order.feign.ContractFeign;
import com.znsd.zl.order.service.IOrderService;
import com.znsd.zl.order.utils.RedisUtils;
import com.znsd.zl.utils.PageUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName TOrder
 * @Description 订单业务层接口实现类
 * @author jaypdd
 * @email jaypdd@163.com
 * @date 2020-08-16 21:16:34
 * @Version v1.0
 */
@Service("orderService")
@Slf4j
public class OrderServiceImpl extends ServiceImpl<IOrderDao, OrderEntity> implements IOrderService {

    @Resource
    IOrderDao iOrderDao;
    @Autowired
    DelayedService delayedService;
    @Autowired
    ContractFeign contractFeign;
    @Resource
    RentDao rentDao;
    @Autowired
    RedisUtils redisUtils;

    /**
     * 分页条件查询
     * @param params 查询条件，支持分页查询
     * @return
     */
    @Override
    public PageUtils queryPage(Integer pageNum, Integer pageSize,Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Page<>(pageNum, pageSize),
                new QueryWrapper<OrderEntity>()
        );
        return new PageUtils(page);
    }
    
    /**
     * @Author tangjun
     * @Description 订单app查询
     * @Date  2020/8/31 0031
     * @Param []
     * @return com.znsd.zl.utils.PageUtils
     **/
    @Override
    public PageUtils findAllTradeOrder(OrderEntity orderEntity) {
        
        List<TradeOrderEntity> records=iOrderDao.findAllTradeOrder(orderEntity);
        PageUtils pageUtils = new PageUtils(records,1,5,10);
        return pageUtils;
    }
    
    @Override
    public PageUtils findAllOrder(Integer pageNum, Integer pageSize,Map<String, Object> params) {
        Object orderNo = params.get("orderNo");
        Page<OrderEntityVo> page=new Page<>(pageNum,pageSize);
        Object t = params.remove("t");
        IPage<OrderEntityVo> allOrder = baseMapper.findAllOrder(page, params);
        List<OrderEntityVo> records=new ArrayList<>();
        Integer stat=pageNum<1?0:pageNum*pageSize-pageSize;
        Integer end=pageNum==0?pageSize:pageNum*pageSize;
        for(int i=stat;i<end;i++){
            System.out.println(i);
            if (i==allOrder.getRecords().size()){
                break;
            }
            records.add(allOrder.getRecords().get(i));

        }
        PageUtils pageUtils = new PageUtils(allOrder);
        pageUtils.setList(records);
        Integer totalCount=allOrder.getRecords().size();
        pageUtils.setTotalCount(totalCount);
        pageUtils.setTotalPage((totalCount+pageSize-1)/pageSize);
        return pageUtils;
    }

    @Override
    public boolean saveOrder(OrderEntity orderEntity) {
        try{
            orderEntity.setOrderStatus(1);
            baseMapper.saveOrder(orderEntity);
            return true;
        }catch (Exception e){
            return false;
        }
    }

    @Override
    public boolean setIsDelete(List<Integer> ids) {

        try{
            for (Integer id:ids){
                baseMapper.setIsDelete(id);
            }
        }catch (Exception e){
            return false;
        }
        return true;
    }

    @Override
    public boolean setStatusSuccess(Integer orderId) {
        OrderEntity orderEntity = baseMapper.selectById(orderId);
        if(orderEntity!=null){
            baseMapper.setStatusSuccess(orderId);
            return true;
        }else{
            return false;
        }
    }

    @Override
    public boolean setStatusCancel(Integer orderId) {
        OrderEntity orderEntity = baseMapper.selectById(orderId);
        if(orderEntity!=null){
            baseMapper.setStatusCancel(orderId);
            return true;
        }
        else{
            return false;
        }

    }


    @Override
    public List<HouseRentVo> findHouseRent(Integer userId){
        return baseMapper.findHouseRent(userId);
    }

    @Override
    public List<UserOrderVo> orderRent(Integer rentId,Integer page,Integer limit) {

        if (page==null||page<0){
            page=0;
        }
        if (limit==null){
            limit=10;
        }
        List<UserOrderVo> userOrderVos = baseMapper.orderRent(rentId,page,limit);

        return userOrderVos;
    }

    /**
     *  下单
     * @param orderEntity 存储订单
     * @param status     支付状态
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String placeAnOrder(@RequestBody OrderEntityVo orderEntity, @RequestParam Boolean status) {
        log.info("order data=====》"+orderEntity + "== payment status=====》"+status);
        // 日期转换器
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 设置系统时区
        TimeZone timeZoneChina = TimeZone.getTimeZone("Asia/Shanghai");
        sdf.setTimeZone(timeZoneChina);
        orderEntity.setCreateTime(sdf.format(new Date()));
        if (!status) {
            // 修改订单状态为未支付
            orderEntity.setOrderStatus(2);
            // 设置一小时订单自动修改状态已取消
            orderEntity.setExpirationTime(System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(15));
            this.baseMapper.insert(orderEntity);
            // 将未支付的订单放入延迟队列中
            delayedService.add(orderEntity);
            return "支付取消";
        }
        // 订单完成
        this.baseMapper.insert(orderEntity);
        log.info("save order data====》"+orderEntity);
        // 封装合同对象来生成双方合同
        ContractEntity contractEntity = new ContractEntity();
        contractEntity.setContractName("contract_name");
        contractEntity.setUserId(orderEntity.getUserId());
        contractEntity.setLandlordId(orderEntity.getLandlordUserId());
        contractEntity.setTemplate(String.valueOf(orderEntity.getTemplateId()));
        contractEntity.setHouseId(orderEntity.getHouseId());
        TimeUnit dayTimeUnit = TimeUnit.DAYS;
        // 获取日历对象
        Calendar calendar = Calendar.getInstance();
        // 偏移几个月
        calendar.add(Calendar.MONTH,orderEntity.getMonth());
        Date endDate = calendar.getTime();
        // 合同时间次日生效
        endDate.setTime(endDate.getTime() + dayTimeUnit.toMillis(1));
        Date beginDate = new Date();
        beginDate.setTime(beginDate.getTime() + dayTimeUnit.toMillis(1));
        // 转换成 中文
        String beginTime = sdf.format(beginDate);
        String endTime = sdf.format(endDate);

        contractEntity.setBeginDate(beginTime);
        contractEntity.setEndDate(endTime);
        log.info("wrapper contract object=====》"+contractEntity);
        Integer msg = 0 ;
        try{
            try {
                msg = contractFeign.add(contractEntity);
            }catch (Exception e) {
                log.error("调用合同增加失败 contractFeign request zlhouse-contract add method error {} ", e.toString());
                log.error("用户信息===》{} 房东信息 {} 房屋编号 {}", orderEntity.getUserId(),
                        orderEntity.getLandlordUserId(), orderEntity.getRentId());
            }
            // 判断出租的房子是整租 还是 合租
            int wholeRent = 24;
            if (wholeRent == orderEntity.getRentWay()) {
                // 通过租房id修改房屋状态  2 已出租
                rentDao.updateRentStatus(orderEntity.getRentId(),2);
            } else {
                // 请求订单查询出租数量
                Integer rentAmount = rentDao.queryRentAmount(orderEntity.getRentId());
                // 请求房屋查询房屋数量
                Integer orderRentPeople = this.baseMapper.queryOrderRentAmount(orderEntity.getRentId());
                // 出租人数已满，修改状态
                if (rentAmount.equals(orderRentPeople) || orderRentPeople >= rentAmount) {
                    // 通过租房id修改房屋状态  2 已出租
                    rentDao.updateRentStatus(orderEntity.getRentId(),2);
                }
            }
        }catch (Exception e) {
            log.error("修改房屋状态异常 {}", e.toString());
        }
        // 给房东添加余额
        try {
            this.baseMapper.userPayment(orderEntity.getLandlordUserId(), orderEntity.getPayment());
        } catch (Exception e) {
            log.error("给房东付款失败 房东编号==》{}  付款金额==》{}   付款用户===》{}",
                    orderEntity.getLandlordUserId(),orderEntity.getPayment(), orderEntity.getUserId());
        }
        try {
            redisUtils.del(String.valueOf(orderEntity.getRentId()));
        }catch (Exception e){
            log.error("redis 操作失败，请手动删除key==={}", orderEntity.getRentId());
        }
        return "支付成功";
    }


}
